//url utils
class UriUtils {
  //uri 地址添加参数
  static String fullUri(String baseUrl,
      {String? path, required Map<dynamic, dynamic>? queryParameters}) {
    String url = baseUrl + (path ?? '');
    if (queryParameters?.isNotEmpty ?? false) {
      String suffix = "";
      queryParameters?.forEach((key, value) {
        suffix += "$key=$value&";
      });
      suffix = suffix.substring(0, suffix.length - 1);
      return '$url?$suffix';
    }
    return url;
  }

  //从url中获取 params
  static Map paramsFormUri(String uri) {
    Map resultMap = Map();
    if (uri.isEmpty) return resultMap;

    String path = '';
    if (uri.contains("?")) {
      path = uri.substring(uri.indexOf("?") + 1, uri.length);
    } else {
      path = uri; //参数串
    }

    if (path.isEmpty) return resultMap; //没有参数串

    List<String> parameters = path.split("&");

    List<MapEntry> paramsList = [];
    parameters.forEach((part) {
      if (part.contains("=")) {
        List<String> params = part.split("=");
        paramsList.add(MapEntry(params[0], params[1]));
      }
    });

    resultMap.clear();
    if (paramsList.isNotEmpty) {
      resultMap.addEntries(paramsList);
      return resultMap;
    }
    return resultMap;
    // return Uri.parse(url)?.queryParameters ?? Map();  不能用 因为涉及  fragment
  }

  static String decodeFull(String uri) {
    if (uri.isEmpty) return '';

    String decodeUrl;
    try {
      decodeUrl = Uri.decodeFull(uri);
    } catch (e) {
      String encodeUrl = Uri.encodeFull(uri); //防止解码步骤有 汉字等字符报错
      decodeUrl = Uri.decodeFull(encodeUrl);
    }
    return decodeUrl;
  }
}
